import style from './index.module.less'
import front from '@imgs/id-front.png'
import back from '@imgs/id-back.png'
import { AddOutline } from 'antd-mobile-icons'
import { awaitWrap, getObjectURL } from '@js/tool'
import { Toast } from 'antd-mobile'
import { requestOneFile } from '@src/assets/js/request'
import { getCardInfoRequest } from './ajax'

// 改变文件
async function changeFile (e, type, setFn) {
  const files = e.target.files
  if (!(files instanceof FileList)) {
    return undefined
  }
  if (files.length === 0 || !(files[0] instanceof File)) {
    return undefined
  }
  const file = files[0]
  if (!['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)) {
    Toast.show('请上传格式为png、jpg或jpeg的图片')
    return undefined
  }
  const f = {
    file,
    url: getObjectURL(file),
    id: '',
    info: {
      name: '',
      num: ''
    }
  }
  await initCardInfo(f, type, setFn)
}

// 获取身份证信息
async function initCardInfo (img, type, setFn) {
  Toast.show({ content: '提交中', icon: 'loading', duration: 0  })
  const [fe, fd] = await awaitWrap(uploadFile(img.file))
  if (fe !== null) {
    return undefined
  }
  if (fd === null) {
    return undefined
  }
  Toast.show({ content: '获取信息中', icon: 'loading', duration: 0  })
  const [e, d] = await awaitWrap(getCardInfoRequest(fd.url, type))
  if (e !== null) {
    console.error(e)
    return undefined
  } else if (d === null) {
    Toast.show({ content: `获取身份证${type}信息失败`, icon: 'fail'  })
    return undefined
  } else {
    Toast.clear()
  }
  setFn({ ...img, id: fd.id, info: d })
}

// 上传图片
async function uploadFile (file) {
  const [e, d] = await awaitWrap(requestOneFile(file))
  if (e !== null) {
    throw new Error(e.message)
  }
  if (d === null) {
    throw new Error('上传文件，返回数据为空')
  }
  return d
}


function Main ({ isFront = false, value, onChange }) {
  return (
    <div className={style.container}>
      <label className={style.inner}>
        <input type='file' className={style.input} multiple={false} onChange={async e => await changeFile(e, isFront ? '正面' : '背面', onChange)} />
        <div className={style.mask} />
        <div className={style.bg}>
          <img src={isFront ? front : back} alt='身份证正面' />
          <div className={style.icon}>
            <AddOutline />
          </div>
        </div>
        <div className={style.notice}>
          {isFront ? <span>请上传身份证人像面</span> : <span>请上传身份证国徽面</span>}
        </div>
        {!!value && <img className={style.pic} src={value.url} alt='' />}
      </label>
    </div>
  )
}

export default Main